import React, {Component} from "react";

class Tabs extends Component{
    constructor() {
        super();
        this.state = {
            currentIndex: 0
        }
    }

    componentDidMount() {
        const { defaultActiveKey } = this.props;
        defaultActiveKey && this.setState({
            currentIndex: defaultActiveKey - 1
        })
    }

    render() {
        const { children } = this.props;
        return (
            <>
                <div className="panel">
                    {
                        children.map(
                            (item, index) => {
                                return <span onClick={() => this.changeIndex(index)}
                                             className={this.check_item_index(index)}
                                             key={index}
                                       >{item.props.name || 'Tab-' + item.key}</span>
                            }
                        )
                    }
                </div>
                <div className="panel-box">
                    {
                        React.Children.map(children,
                            (item, index) => {
                                return <div className={this.check_item_index(index)}
                                            key={index}
                                       >{item.props.children}</div>
                            }
                        )
                    }
                </div>
            </>
        )
    }

    check_item_index(index){
        return index === this.state.currentIndex ? "active" : ""
    }

    changeIndex (index){
        this.setState({
            currentIndex: index
        }, () => {
            this.props.onChange(index + 1)
        })
    }
}

export default Tabs;